import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:permission_handler/permission_handler.dart';

// const store_rId = '77289A5EC1EDEB725AB1E7FCE3F8BE514091FEBE44315EC1AF6B410C415CA4E95728211641DC8DF8A7B7A7F18A080583F534578BFBAA6E67A6E96DC4C072195E19E1160013745AA0BE9B0FBD01BA693F7AC4FFEDBCB8C802DF3B63D574C82F06FB0E2EAB50E78B8D0EBA084B39D770A80ACA887501974F1009BC91CF2A29E2DE3897EF5486707CFC2E6CA12D3BDE3FEDD1FE8FEBD11EB9F34BEC9EA485245BFE5029D96FE136CDDE897A5643D8781EFC197D1792C8D8A9FCB14A2AAC50714C8E286900D60BF5CAB82EE36D9A4FF40B25';
// const store_aId = '77289A5EC1EDEB725AB1E7FCE3F8BE514091FEBE44315EC1AF6B410C415CA4E95728211641DC8DF8A7B7A7F18A080583F534578BFBAA6E679D909C68C9A5ECF3EB7C76E807335C092DD9F63468CCB418216CA9EB4FCAC474D9F4D366D2D975510CFEE7299E02904A86F3A23298A75695F30B42E32E427C20252F31EAF3A16EB2E4EDA4FFDF4791F94EFA3096F17A4EBADFA45C6790C68CBB93F332F0CDB8E5B6501954A44EA4D016FB18488298C39AB5B9E45C8039807D695A7753201CC2959494A8AC39AB4CBBCEAA5D86E20BC404CB';
const store_rId = '77289A5EC1EDEB725AB1E7FCE3F8BE514091FEBE44315EC1AF6B410C415CA4E95728211641DC8DF8A7B7A7F18A080583FE80827D6DA030CEF1E1ACFDFCE6AAF071100AB94F018616A550A2A2481A883615AB9C3BEC125FE63908CD31ACA50E7D93CDBD4928910F885C4FD4C7612CE96A65BA3A10421600FFE2C4329539EA5C49FF5332B191688532E9AA78EC63A052DA964D136535C791A8A0DEB9F2D48FE0F64805265690409380641C4293B92BCD870FFEA32C9D43B320F0632829AFB74FF440288A15B21FAE37';
const store_aId = '77289A5EC1EDEB725AB1E7FCE3F8BE514091FEBE44315EC1AF6B410C415CA4E95728211641DC8DF8A7B7A7F18A080583FE80827D6DA030CEF1E1ACFDFCE6AAF071100AB94F018616A550A2A2481A883615AB9C3BEC125FE63908CD31ACA50E7D93CDBD4928910F885C4FD4C7612CE96A65BA3A10421600FF5E6A2D8A96CF600C0303E98026AF429CB45FB60A505D5B87DA686D92C42EC29B34C233637E8C03A80C355A8348BD505DF04B0FA5A6038FAA56DFBB5B3D9CA30B635A4A067594BA05B27F9426C32D38F4';
class ShopWebView extends StatefulWidget {
  @override
  State createState() => _ShopWebViewState();

}

class _ShopWebViewState extends State<ShopWebView> {
  InAppWebViewController? _controller;
  // final initUrl = "http://app-mall-uat.livanauto.com/mall/items/116800100451012";//"https://www.baidu.com";//
  // final initUrl = "https://app-mall.livanauto.com/mall/buyer/orders?tab=all";//"https://www.baidu.com";//
  final initUrl = "http://app-mall.livanauto.com/mall/items/116800100417044";//"https://www.baidu.com";//"https://www.baidu.com";//
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("商城页面"),),
      body: InAppWebView(
        initialUrlRequest: URLRequest(url: Uri.parse(initUrl)),
        // initialUserScripts: UnmodifiableListView([
        //   UserScript(
        //     source: "",
        //     injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START,
        //   )
        // ]),
        initialOptions: InAppWebViewGroupOptions(
          android: AndroidInAppWebViewOptions(
            useHybridComposition: true,
          ),
          crossPlatform: InAppWebViewOptions(
            useShouldOverrideUrlLoading: true,
            allowFileAccessFromFileURLs: true,
            mediaPlaybackRequiresUserGesture: false,
            userAgent: "Mozilla/5.0 (Linux; Android 12; NAM-AL00 Build/HUAWEINAM-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/92.0.4515.105 Mobile Safari/537.36 livan;app/1.0.0",// WebViewInfoChannel.getUserAgent(),
            // userAgent: "livan;app/1.0.0",// WebViewInfoChannel.getUserAgent(),
            javaScriptEnabled: true,
            javaScriptCanOpenWindowsAutomatically: true,
            // clearCache: true,
          ),
        ),
        onCreateWindow: (InAppWebViewController controller, CreateWindowAction createWindowAction) async {
          return handleCreateWindow(controller, createWindowAction, initUrl);
        },
        onWebViewCreated: (controller) async {
          _controller = controller;

          await controller.addWebMessageListener(WebMessageListener(
            jsObjectName: "flutterLogin",
            onPostMessage: (String? m, Uri? u, bool b, JavaScriptReplyProxy r) {
              print("flutterLogin --- m: ${m}");

            },
          ));
          await controller.addWebMessageListener(WebMessageListener(
            jsObjectName: "navigatorPop",
            onPostMessage: (String? m, Uri? s, bool b, JavaScriptReplyProxy r) {
              print("js dispatch navigator pop --- ");
              Navigator.pop(context);
            },
          ));
          await controller.addWebMessageListener(WebMessageListener(
              jsObjectName: "goodsShare",
              onPostMessage: (String? m, Uri? u, bool b, JavaScriptReplyProxy r) {
                print(
                    "goods_share - message: ${m ?? 'empty'};uri: ${u?.toString() ?? 'empty'}; isMainFrame: ${b}");
              }));
          await controller.addWebMessageListener(WebMessageListener(
            jsObjectName: "openCustomerService",
            onPostMessage: (String? m, Uri? u, bool b, JavaScriptReplyProxy r) {
              // if (!Http.isLogin) {
              //   Http.clearAuthorization();
              //   LocalLog.d("shop_webview_logic: 179", tag: "fire_to_login_event");
              //   EventBus bus = Get.find();
              //   bus.fire(ToLoginEvent());
              // } else {
              //   PersonUserUserToFmlEntity? entity = AppState().readUserInfo();
              //   if (entity == null || entity.userId == null) return;
              //   CustomerServiceMc.openCustomerService(entity.userId.toString());
              // }
            },
          ));
          await controller.addWebMessageListener(WebMessageListener(
            jsObjectName: "changeWebViewTitle",
            onPostMessage: (String? m, Uri? u, bool b, JavaScriptReplyProxy r) {
              if (m == null) return;
              // state.webViewTitle.value = m;
            },
          ));
          await controller.addWebMessageListener(WebMessageListener(
            jsObjectName: "requestPermission",
            onPostMessage: (String? m, Uri? u, bool b, JavaScriptReplyProxy r) async {
              print("JavascriptChannel common/shopping/cart: ${m}");
              PermissionStatus permissionCameraStatus =
              await Permission.camera.status;
              PermissionStatus permissionStorageStatus =
              await Permission.storage.status;
              if (permissionCameraStatus != PermissionStatus.granted ||
                  permissionStorageStatus != PermissionStatus.granted) {
                // 权限未开启

                Map<Permission, PermissionStatus> statuses = await [
                  Permission.camera,
                  Permission.storage,
                ].request();
                if ((statuses[Permission.camera] == PermissionStatus.granted ||
                    statuses[Permission.camera] ==
                        PermissionStatus.limited) &&
                    statuses[Permission.storage] == PermissionStatus.granted) {
                  // 权限开启
                  print("JavascriptChannel requestPermission: 拉起选择框");
                } else {
                  print("JavascriptChannel requestPermission:未开启权限");
                }
              } else {
                // 权限开启
                print("JavascriptChannel requestPermission: 拉起选择框");
              }
            },
          ));
          await controller.addWebMessageListener(WebMessageListener(
            jsObjectName: "updateCookie",
            onPostMessage: (String? m, Uri? u, bool b, JavaScriptReplyProxy r) async {
              if (u == null) return;
              // await setCookiesByCookieManager(u);
              // await logDocumentCookies();
            },
          ));
          await controller.addWebMessageListener(WebMessageListener(
            jsObjectName: "setCookieByOne",
            onPostMessage: setCookieByOne,
          ));
          await controller.addWebMessageListener(WebMessageListener(
            jsObjectName: "setCookieByTow",
            onPostMessage: setCookieByTow,
          ));
          await controller.addWebMessageListener(WebMessageListener(
            jsObjectName: "printCookies",
            onPostMessage: printCookies,
          ));
          final uri = Uri.parse(initUrl);
          try {
            await setCookiesByCookieManager(uri);
            print("handle create window: ${uri.toString()}");
          } catch (e) {
            print("handle create window - error: ${e}, uri: ${initUrl}");
            await setCookie();
          }
          // await logDocumentCookies();
          await controller.loadUrl(urlRequest: URLRequest(url: uri));
        },
        shouldOverrideUrlLoading: handleOverrideUrlLoading,
        onLoadStart: handleLoadStart,
        onProgressChanged: handleProgressChanged,
        onLoadStop: handleLoadStop,
      ),
    );
  }
  Future<bool> handleCreateWindow(InAppWebViewController controller,
      CreateWindowAction createWindowAction, String initUrl) async {
    try {
      final uri = Uri.parse(initUrl);
      await setCookiesByCookieManager(uri);
      print("handle create window: ${uri.toString()}");
    } catch (e) {
      print("handle create window - error: ${e}, uri: ${initUrl}");
      await setCookie();
    }
    // await logDocumentCookies();
    return true;
  }

  String? _currentUrl;
  Future<NavigationActionPolicy?> handleOverrideUrlLoading(
      InAppWebViewController controller,
      NavigationAction navigationAction) async {
    print("---------------------------   handleOverrideUrlLoading");
    final request = navigationAction.request;
    print("----即将跳转到:${request.url}------");
    String url = request.url.toString();
    _currentUrl = url;
    final uri = Uri.tryParse(url);
    if (uri != null) {
      await setCookiesByCookieManager(uri);
      // await logDocumentCookies();
    }
    return NavigationActionPolicy.ALLOW;
  }

  handleProgressChanged(InAppWebViewController controller, int progress) {

  }

  handleLoadStart(InAppWebViewController controller, Uri? url) async {
    print("---------------------------   handleLoadStart");
    String jsString = "document.title";
    if (_controller != null) {
      print("-----获取商城页面H5的titile------");
      try {
        var result =
        await _controller?.evaluateJavascript(source: jsString);
        print("-----shop page current title:${result}-----");
      } catch (e) {
        print("----get shop page title error:${e}------");
      }
    } else {
      print("------shop webview controller is not exist------");
    }
  }

  handleLoadStop(InAppWebViewController controller, Uri? url) async {
    print("---------------------------   handleLoadStop");
    print("-------page:${url} load finished------");
    // String cookie = "document.cookie = 'aId=';document.cookie = 'rId='";
    // state.controller?.runJavascript(cookie);
    // await state.controller?.evaluateJavascript(source: cookie);
    if (url == null) return;
    // setCookiesByCookieManager(url);
    // setCookie();
    try {
      await setCookiesByCookieManager(url);
      print("handle create window: ${url.toString()}");
    } catch (e) {
      print("handle create window - error: ${e}, uri: ${url.toString()}");
      await setCookie();
    }
    await logDocumentCookies();
  }

  setCookie() async {
    String aId = store_aId;
    String rId = store_rId;
    print("set cookie: \n aId = ${aId} \n rId = ${rId} \n");
    // String cookie = "document.cookie = 'aId=${aId}';document.cookie = 'rId=${rId}'";
    String cookie = "document.cookie = 'aId=${aId}';document.cookie = 'rId=${rId}'";
    await _controller?.evaluateJavascript(source: cookie);
  }
  setCookiesByCookieManager(Uri url) async {
    final tag = "set_cookies_by_cookie_manager";
    String aId = store_aId;
    String rId = store_rId;
    if (_controller == null) {
      print("*****************************  control 尚未设置");
      return;
    }
    print("setCookiesByCookieManager - ： ${url}, ${aId}, ${rId}");
    String cookie =
        "document.cookie = 'aId=${aId}';document.cookie = 'rId=${rId}'";
    // state.controller?.runJavascript(cookie);
    await _controller?.evaluateJavascript(source: cookie);

    CookieManager cookieManager = CookieManager.instance();
    final expiresDate =
        DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;
    await cookieManager.setCookie(
      url: url,
      name: "aId",
      value: aId,
      expiresDate: expiresDate,
    );
    await cookieManager.setCookie(
      url: url,
      name: "rId",
      value: rId,
      expiresDate: expiresDate,
    );
    String printCookie = """
    console.log('print_cookie: ',document.cookie)
    """;
    await _controller?.evaluateJavascript(source: printCookie);
  }

  setCookieByOne(String? m, Uri? u, bool b, JavaScriptReplyProxy r) async {
    if (u == null) return;
    await setCookiesByCookieManager(u);
    // await logDocumentCookies();
  }

  setCookieByTow(String? m, Uri? u, bool b, JavaScriptReplyProxy r) async {
    if (u == null) return;
    await setCookie();
    // await logDocumentCookies();
  }

  printCookies(String? m, Uri? u, bool b, JavaScriptReplyProxy r) async {
    if (u == null) return;
    CookieManager cookieManager = CookieManager.instance();
    final list = await cookieManager.getCookies(url: u);
    list.forEach((element) {
      print("cookie item: ${element}");
    });
  }

  logDocumentCookies() async {
    final tempController = _controller;
    if (tempController == null) {
      print("controller is null");
      return;
    }
    try {
      String jsString = "window.printCookies.postMessage()";// "document.cookie";
      var result = await _controller?.evaluateJavascript(source: jsString);
      print("document cookies is ${result}");
    } catch (e) {
      print("get cookie error: ${e}");
    }
  }
}